package p.ithorns.framework.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 *
 * @author ithorns
 * @version 1.0
 * @date 2020/4/1 9:00
 */
public class DeviceUtil {

    private final static Logger log = LoggerFactory.getLogger(DeviceUtil.class);

    private final static String SN = getSn();

    /**
     * MainboardSN
     *
     * @return String
     */
    private static String getMainboardSN() {
        String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                + "Set colItems = objWMIService.ExecQuery _ \n"
                + "   (\"Select * from Win32_BaseBoard\") \n"
                + "For Each objItem in colItems \n"
                + "    Wscript.Echo objItem.SerialNumber \n"
                + "    exit for  ' do the first cpu only! \n" + "Next \n";
        return readDeviceNo(vbs);
    }

    /**
     * HardDiskSN
     *
     * @return String
     */
    private static String getHardDiskSN() {
        String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                + "Set colItems = objWMIService.ExecQuery _ \n"
                + "   (\"Select * from Win32_DiskDrive\") \n"
                + "For Each objItem in colItems \n"
                + "    Wscript.Echo objItem.SerialNumber \n"
                + "    exit for  ' do the first cpu only! \n" + "Next \n";
        return readDeviceNo(vbs);
    }


    /**
     * 获取CPU序列号
     *
     * @return String
     */
    private static String getCPUSerial() {
        String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                + "Set colItems = objWMIService.ExecQuery _ \n"
                + "   (\"Select * from Win32_Processor\") \n"
                + "For Each objItem in colItems \n"
                + "    Wscript.Echo objItem.ProcessorId \n"
                + "    exit for  ' do the first cpu only! \n" + "Next \n";

        String result = readDeviceNo(vbs);
        if (StringUtils.isEmpty(result)) {
            result = "无CPU_ID被读取";
        }
        return result;
    }

    private static List<String> getLocalHostLANAddress() throws UnknownHostException, SocketException {
        List<String> ips = new ArrayList<String>();
        Enumeration<NetworkInterface> interfs = NetworkInterface.getNetworkInterfaces();
        while (interfs.hasMoreElements()) {
            NetworkInterface interf = interfs.nextElement();
            Enumeration<InetAddress> addres = interf.getInetAddresses();
            while (addres.hasMoreElements()) {
                InetAddress in = addres.nextElement();
                if (in instanceof Inet4Address) {
                    log.debug("v4:" + in.getHostAddress());
                    if (!"127.0.0.1".equals(in.getHostAddress())) {
                        ips.add(in.getHostAddress());
                    }
                }
            }
        }
        return ips;
    }

    /**
     * MAC
     *
     * @return String
     */
    private static String getMac() {
        try {
            String resultStr = "";
            List<String> ls = getLocalHostLANAddress();
            for (String str : ls) {
                InetAddress ia = InetAddress.getByName(str);
                byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < mac.length; i++) {
                    if (i != 0) {
                        sb.append("-");
                    }
                    String s = Integer.toHexString(mac[i] & 0xFF);
                    sb.append(s.length() == 1 ? 0 + s : s);
                }
                resultStr += sb.toString().toUpperCase() + ",";
            }
            return resultStr;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    private static String readDeviceNo(String vbs) {
        StringBuilder result = new StringBuilder();
        BufferedReader input = null;
        try {
            File file = File.createTempFile("realhowto", ".vbs");
            file.deleteOnExit();
            FileWriter fw = new FileWriter(file);
            fw.write(vbs);
            fw.close();
            String path = file.getPath().replace("%20", " ");
            Process p = Runtime.getRuntime().exec("cscript //NoLogo " + path);
            input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = input.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            if (null != input) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return StringUtils.trimAllWhitespace(result.toString());

    }

    /***************************linux*********************************/

    private static String executeLinuxCmd(String cmd) {

        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmd);
        } catch (IOException e) {
            log.warn("The command failed to execute: [{}]", cmd);
            return null;
        }

        if (process == null) {
            return null;
        }

        try (
                InputStream in = process.getInputStream();
                BufferedReader bs = new BufferedReader(new InputStreamReader(in));
        ) {
            //log.debug("Got cmd job: {}", cmd);
            StringBuffer out = new StringBuffer();
            byte[] b = new byte[2048];
            for (int n; (n = in.read(b)) != -1; ) {
                out.append(new String(b, 0, n));
            }

            process.destroy();
            return out.toString();
        } catch (Exception e) {
            log.warn(e.getMessage());
        }

        return null;
    }

    /**
     * @param cmd    命令语句
     * @param record 要查看的字段
     * @param symbol 分隔符
     * @return String
     */
    private static String getSerialNumber(String cmd, String record, String symbol) {
        String execResult = executeLinuxCmd(cmd);

        if (StringUtils.isEmpty(execResult)) {
            return "";
        }

        String[] infos = execResult.split("\n");

        for (String info : infos) {
            if (info.contains(record)) {
                info = StringUtils.trimAllWhitespace(info);
                String[] sn = info.split(symbol);
                if (sn.length > 1) {
                    return sn[1];
                }
            }
        }

        return "";
    }

    private static String getSerialNumber(String cmd) {
        String result = executeLinuxCmd(cmd);
        return StringUtils.trimAllWhitespace(result);
    }

    /**
     * 获取CPUID、硬盘序列号、MAC地址、主板序列号
     *
     * @return String
     */
    public static String getSn() {

        return "cac9a18c500dd6078251014de0f03430";

//        if (StringUtil.isNotBlank(DeviceUtil.SN)) {
//            return DeviceUtil.SN;
//        }
//
//        StringBuilder deviceNo = new StringBuilder();
//
//        //System.out.println("===============================================================");
//        //System.out.println("Generating Device SN for OS type:  " + SystemUtils.getOsName());
//
//        log.info("==================================================================");
//        log.info("Generating Device SN for OS type: {}", SystemUtils.getOsName());
//
//        if (SystemUtils.isLinux()) {
//
//            /**
//             * linux
//             * cpuid : dmidecode -t processor | grep 'ID'
//             * mainboard : dmidecode |grep 'Serial Number'
//             * disk : fdisk -l
//             * mac : ifconfig -a
//             */
//            String cpuid = getSerialNumber("dmidecode -t processor | grep 'ID'", "ID", ":");
//            log.debug("CPU ID: [{}]", cpuid);
//
//            String serialNumber = getSerialNumber("dmidecode -s system-serial-number");
//            //getSerialNumber("dmidecode |grep 'Serial Number'", "Serial Number", ":");
//            log.debug("System Serial Number: [{}]", serialNumber);
//
//            //String diskNumber = getSerialNumber("fdisk -l", "Disk identifier", ":");
//            //log.debug("Disk Number: {}", diskNumber);
//
//            String mac = getMac();
//            //getSerialNumber("ifconfig -a", "ether", " ");
//            log.debug("Local Mac: [{}]", mac);
//
//            String oem = getSerialNumber("dmidecode -t 11 | grep 'String 1' ", "String 1", ":");
//            log.debug("OEM Info: [{}]", oem);
//
//            deviceNo.append(cpuid)
//                    .append(serialNumber)
//                    .append(mac)
//                    .append(oem);
//
//        } else if (SystemUtils.isWindows()) {
//            String cpuid = getCPUSerial();
//            String mainboard = getMainboardSN();
//            String disk = getHardDiskSN();
//            String mac = getMac();
//
//            log.debug("CPU SN: {}", cpuid);
//            log.debug("MainBoard SN: {}", mainboard);
//            log.debug("Disk SN:{}", disk);
//            log.debug("MAC SN: {}", mac);
//
//            deviceNo.append(cpuid)
//                    .append(mainboard)
//                    .append(disk);
//
//        } else {
//            log.warn("The OS is not supported.");
//            throw new UnsupportedOperationException();
//        }
//
//        String md5 = DigestUtils.md5Hex(deviceNo.toString());
//
//        log.info("Device SN was generated ==> [{}]", md5);
//        log.info("==================================================================");
//        // System.out.println("Device SN was generated ==> ["+ md5+ "]");
//        //System.out.println("===============================================================");
//
//        return md5;
    }

}
